package com.lzs.common.service.impl;

import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.google.common.base.CaseFormat;
import com.google.common.io.Files;
import com.lzs.common.config.Constant;
import com.lzs.common.dao.SysMenuDao;
import com.lzs.common.dto.PageQuery;
import com.lzs.common.dao.DbFieldDao;
import com.lzs.common.dao.DbTableDao;
import com.lzs.common.dto.GenerateCodeDto;
import com.lzs.common.dto.table.OneToManyTableDto;
import com.lzs.common.enums.field.FieldInputType;
import com.lzs.common.pojo.common.DbField;
import com.lzs.common.pojo.common.DbTable;
import com.lzs.common.pojo.common.SysMenu;
import com.lzs.common.pojo.common.bo.DbFieldBo;
import com.lzs.common.service.CodeGenerateService;
import com.lzs.common.utils.CommonStringUtils;
import com.lzs.common.utils.JudgeSystemUtil;
import com.lzs.common.utils.easy.EasyExcelUtils;
import com.lzs.common.utils.easy.ExcelDtoClassLoader;
import com.lzs.common.vo.CommonResult;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.io.*;
import java.util.*;

@Service
@Slf4j
public class CodeGenerateServiceImpl implements CodeGenerateService {

    @Autowired
    private DbTableDao dbTableDao;
    @Autowired
    private DbFieldDao dbFieldDao;
    @Autowired
    private SysMenuDao sysMenuDao;

    @Override
    public CommonResult<DbTable> tableByPage(PageQuery pageQuery, String tableName) {
        dbTableDao.tableByPage(pageQuery.toPage(), Constant.DB_NAME,tableName);
        return pageQuery.toCommonResult();
    }

    /**
     * 根据表名称查询所有字段
     * @param tableName
     * @return
     */
    @Override
    public CommonResult<DbFieldBo> fieldByTable(String tableName) {
        List<DbField> fieldList = dbFieldDao.fieldByTable(Constant.DB_NAME,tableName);
        List<DbFieldBo> fieldBoList = new ArrayList<>(fieldList.size());
        for (DbField dbField : fieldList) {
            DbFieldBo dbFieldBo = new DbFieldBo();
            BeanUtils.copyProperties(dbField,dbFieldBo);
            //主键
            if (dbField.getColumnKey().equals("PRI")) {
                dbFieldBo.setPrimaryKey(true);
            }else {
                dbFieldBo.setPrimaryKey(false);
            }
            fieldBoList.add(dbFieldBo);
        }
        return CommonResult.rows(fieldBoList);
    }

    @Override
    public CommonResult generateCode(GenerateCodeDto dto) {
        //下划线转驼峰
        dto.setTableName(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, dto.getTable_name()));
        //驼峰转首字母大写的驼峰
        dto.setT_ableName(CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,dto.getTableName()));
        dto.setP_rimaryKeyName(CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,dto.getPrimaryKeyName()));
        //设置别名
        dto.setAsTableName(CommonStringUtils.toAsName(dto.getT_ableName()));
        if (StringUtils.isBlank(dto.getTableComment())) {
            dto.setTableComment(dto.getTable_name());
        }
        String projectPath = Constant.PROJECT_PATH;

        //查询字段
        List<GenerateCodeDto.GenerateCodeFieldDto> whereFieldList = new ArrayList<>();
        //列表显示字段
        List<GenerateCodeDto.GenerateCodeFieldDto> showFieldList = new ArrayList<>();
        //保存字段
        List<GenerateCodeDto.GenerateCodeFieldDto> saveFieldList = new ArrayList<>();
        //修改字段list
        List<GenerateCodeDto.GenerateCodeFieldDto> updateFieldList = new ArrayList<>();
        //是否可导入/导出
        List<GenerateCodeDto.GenerateCodeFieldDto> InOutFieldList = new ArrayList<>();

        List<GenerateCodeDto.GenerateCodeFieldDto> tableFieldList = dto.getTableFieldList();
        for (GenerateCodeDto.GenerateCodeFieldDto generateCodeFieldDto : tableFieldList) {
            if (Objects.isNull(generateCodeFieldDto.getPrimaryKey())) {
                generateCodeFieldDto.setPrimaryKey(false);
            }
            if(StringUtils.isBlank(generateCodeFieldDto.getColumnComment())){
                generateCodeFieldDto.setColumnComment(generateCodeFieldDto.getColumnName());
            }
            //设置字段名
            generateCodeFieldDto.setColumn_name(generateCodeFieldDto.getColumnName());
            //下划线转驼峰
            String columnName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, generateCodeFieldDto.getColumnName());
            generateCodeFieldDto.setColumnName(columnName);
            //驼峰转首字母大写
            String columnNameTitleCase = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,columnName);
            generateCodeFieldDto.setColumnNameTitleCase(columnNameTitleCase);
            //转大写
            generateCodeFieldDto.setDataType(generateCodeFieldDto.getDataType().toUpperCase());

            //是否为查询字段
            if (StringUtils.isNotBlank(generateCodeFieldDto.getFieldSearchType())) {
                whereFieldList.add(generateCodeFieldDto);
            }
            //是否为列表显示字段
            if (Objects.nonNull(generateCodeFieldDto.getFieldShowType())) {
                showFieldList.add(generateCodeFieldDto);
            }
            //是否为保存字段
            if (Objects.nonNull(generateCodeFieldDto.getFieldInputType())) {
                saveFieldList.add(generateCodeFieldDto);
            }
            //是否为修改字段
            if (Objects.nonNull(generateCodeFieldDto.getHaveEdit())) {
                updateFieldList.add(generateCodeFieldDto);
            }
            if (BooleanUtils.isTrue(generateCodeFieldDto.getInOut())) {
                InOutFieldList.add(generateCodeFieldDto);
            }
            if (StringUtils.isNotBlank(generateCodeFieldDto.getJoinDict())){
                dto.setHaveJoinDict(true);
            }
            //是否存在图片
            if (generateCodeFieldDto.getFieldInputType().equals(FieldInputType.IMAGE_UPLOAD)) {
                dto.setHaveImgField(true);
            }
            //是否存在富文本
            if (generateCodeFieldDto.getFieldInputType().equals(FieldInputType.RICH_TEXT)) {
                dto.setHaveRichTextEditor(true);
            }

        }
        OneToManyTableDto oneToManyTableDto = dto.getOneToManyTableDto();
        if (Objects.isNull(oneToManyTableDto)){
            oneToManyTableDto = new OneToManyTableDto();
            oneToManyTableDto.setOpen(false);
        }
        //表连接 下划线
        String join_table = oneToManyTableDto.getJoinTable();
        if (oneToManyTableDto.getOpen()){
            oneToManyTableDto.setJoin_table(join_table);
            //下划线转驼峰
            oneToManyTableDto.setJoinTable(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, oneToManyTableDto.getJoinTable()));
            //驼峰转首字母大写
            oneToManyTableDto.setJ_oinTable(CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,oneToManyTableDto.getJoinTable()));
            oneToManyTableDto.setJ_oinField(CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,oneToManyTableDto.getJoinField()));
            //下划线转驼峰
            String joinTableField = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, oneToManyTableDto.getJoinTableField());
            oneToManyTableDto.setJoinTableFieldHump(joinTableField);
            //首字母大写
            oneToManyTableDto.setJ_oinTableField(CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,joinTableField));
            if (StringUtils.isBlank(oneToManyTableDto.getTableComment())) {
                oneToManyTableDto.setTableComment(oneToManyTableDto.getJoinTable());
            }
            //设置连接表的备注
            PageQuery pageQuery = new PageQuery();
            pageQuery.setPageNum(0);
            pageQuery.setPageSize(2);
            CommonResult<DbTable> dbTableCommonResult = this.tableByPage(pageQuery, join_table);
            DbTable dbTable = dbTableCommonResult.getRows().get(0);
            if(StringUtils.isBlank(dbTable.getTableComment())){
                oneToManyTableDto.setTableComment(oneToManyTableDto.getJoinTable());
            }else {
                oneToManyTableDto.setTableComment(dbTable.getTableComment());
            }
            //查询字段
            List<GenerateCodeDto.GenerateCodeFieldDto> whereFieldListJoinTable = new ArrayList<>();
            //列表显示字段
            List<GenerateCodeDto.GenerateCodeFieldDto> showFieldListJoinTable = new ArrayList<>();
            //保存字段
            List<GenerateCodeDto.GenerateCodeFieldDto> saveFieldListJoinTable = new ArrayList<>();
            //修改字段list
            List<GenerateCodeDto.GenerateCodeFieldDto> updateFieldListJoinTable = new ArrayList<>();
            List<GenerateCodeDto.GenerateCodeFieldDto> tableFieldListJoinTable = oneToManyTableDto.getTableFieldList();
            for (GenerateCodeDto.GenerateCodeFieldDto generateCodeFieldDto : tableFieldListJoinTable) {
                if (Objects.isNull(generateCodeFieldDto.getPrimaryKey())) {
                    generateCodeFieldDto.setPrimaryKey(false);
                }
                if(generateCodeFieldDto.getPrimaryKey()){
                    oneToManyTableDto.setPrimaryKeyField(generateCodeFieldDto);
                }
                if(StringUtils.isBlank(generateCodeFieldDto.getColumnComment())){
                    generateCodeFieldDto.setColumnComment(generateCodeFieldDto.getColumnName());
                }
                //设置字段名
                generateCodeFieldDto.setColumn_name(generateCodeFieldDto.getColumnName());
                //下划线转驼峰
                String columnName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, generateCodeFieldDto.getColumnName());
                generateCodeFieldDto.setColumnName(columnName);
                //驼峰转首字母大写
                String columnNameTitleCase = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,columnName);
                generateCodeFieldDto.setColumnNameTitleCase(columnNameTitleCase);
                //转大写
                generateCodeFieldDto.setDataType(generateCodeFieldDto.getDataType().toUpperCase());

                //是否为查询字段
                if (StringUtils.isNotBlank(generateCodeFieldDto.getFieldSearchType())) {
                    whereFieldListJoinTable.add(generateCodeFieldDto);
                }
                //是否为列表显示字段
                if (Objects.nonNull(generateCodeFieldDto.getFieldShowType())) {
                    showFieldListJoinTable.add(generateCodeFieldDto);
                }
                //是否为保存字段
                if (Objects.nonNull(generateCodeFieldDto.getFieldInputType())) {
                    saveFieldListJoinTable.add(generateCodeFieldDto);
                }
                //是否为修改字段
                if (Objects.nonNull(generateCodeFieldDto.getHaveEdit())) {
                    updateFieldListJoinTable.add(generateCodeFieldDto);
                }
                if (StringUtils.isNotBlank(generateCodeFieldDto.getJoinDict())){
                    oneToManyTableDto.setHaveJoinDict(true);
                }
                //是否存在图片
                if (generateCodeFieldDto.getFieldInputType().equals(FieldInputType.IMAGE_UPLOAD)) {
                    oneToManyTableDto.setHaveImgField(true);
                }
                //是否存在富文本
                if (generateCodeFieldDto.getFieldInputType().equals(FieldInputType.RICH_TEXT)) {
                    oneToManyTableDto.setHaveRichTextEditor(true);
                }
            }
            oneToManyTableDto.setWhereFieldList(whereFieldListJoinTable);
            oneToManyTableDto.setShowFieldList(showFieldListJoinTable);
            oneToManyTableDto.setSaveFieldList(saveFieldListJoinTable);
            oneToManyTableDto.setUpdateFieldList(updateFieldListJoinTable);
            //设置连接表的字段 sys_dict_detail
//            CommonResult<DbFieldBo> dbFieldBoCommonResult = this.fieldByTable(join_table);
//            List<DbFieldBo> dbFieldBoList = dbFieldBoCommonResult.getRows();
//            List<GenerateCodeDto.GenerateCodeFieldDto> oneToManyTableFieldList = new ArrayList<>(dbFieldBoList.size());
//            for (DbFieldBo dbFieldBo : dbFieldBoList) {
//                GenerateCodeDto.GenerateCodeFieldDto generateCodeFieldDto = new GenerateCodeDto.GenerateCodeFieldDto();
//                //下划线转驼峰
//                generateCodeFieldDto.setColumnName(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, dbFieldBo.getColumnName()));
//                generateCodeFieldDto.setColumn_name(dbFieldBo.getColumnName());
//                generateCodeFieldDto.setDataType(dbFieldBo.getDataType().toUpperCase());
//                generateCodeFieldDto.setJdbcType(dbFieldBo.getDataType());
//                generateCodeFieldDto.setColumnComment(dbFieldBo.getColumnComment());
//                if (StringUtils.isBlank(generateCodeFieldDto.getColumnComment())) {
//                    generateCodeFieldDto.setColumnComment(generateCodeFieldDto.getColumnName());
//                }
//                generateCodeFieldDto.setFieldShowType(FieldShowType.TEXT);
//                generateCodeFieldDto.setHaveEdit(true);
//                //主键
//                if (dbFieldBo.getColumnKey().equals("PRI")) {
//                    generateCodeFieldDto.setPrimaryKey(true);
//                    oneToManyTableDto.setPrimaryKeyField(generateCodeFieldDto);
//                }else {
//                    generateCodeFieldDto.setPrimaryKey(false);
//                }
//                oneToManyTableFieldList.add(generateCodeFieldDto);
//            }
//            oneToManyTableDto.setTableFieldList(oneToManyTableFieldList);
        }


        dto.setWhereFieldList(whereFieldList);
        dto.setShowFieldList(showFieldList);
        dto.setSaveFieldList(saveFieldList);
        dto.setUpdateFieldList(updateFieldList);

        String templateJavaPath = projectPath+"system-modules"+File.separator+"src"+File.separator+"main"+File.separator+"resources"+File.separator+"generateCode"+File.separator+"java";
        String templateJsPath = projectPath+"system-modules"+File.separator+"src"+File.separator+"main"+File.separator+"resources"+File.separator+"generateCode"+File.separator+"js";

        String baseSystemPath = projectPath+"system-modules"+File.separator+"src"+File.separator+"main"+File.separator;
        String baseCommonPath = projectPath+"common-modules"+File.separator+"src"+File.separator+"main"+File.separator;
        String javaSystemModulesBasePath = baseSystemPath+"java"+File.separator+"com"+File.separator+"lzs"+File.separator+"system"+File.separator+"modules"+File.separator+dto.getModuleName();//目标路径【指向你自己的类文件存放路径】
        String javaCommonModulesBasePath = baseCommonPath+"java"+File.separator+"com"+File.separator+"lzs"+File.separator+"common";//目标路径【指向你自己的类文件存放路径】
        String resourceBasePath = baseSystemPath+File.separator+"resources"+File.separator+"mappers"+File.separator+"modules"+File.separator+dto.getModuleName();//目标路径【指向你自己的类文件存放路径】
        //java
        genFileWithTemplate(templateJavaPath,javaSystemModulesBasePath+File.separator+"controller","controller.ftl",dto.getT_ableName()+"Controller.java",dto);
        genFileWithTemplate(templateJavaPath,javaSystemModulesBasePath+File.separator+"dao","dao.ftl",dto.getT_ableName()+"Dao.java",dto);
        genFileWithTemplate(templateJavaPath,javaSystemModulesBasePath+File.separator+"dto","getByPageDto.ftl",dto.getT_ableName()+"GetByPageDto.java",dto);
        genFileWithTemplate(templateJavaPath,resourceBasePath,"mapper.ftl",dto.getT_ableName()+"Mapper.xml",dto);
        genFileWithTemplate(templateJavaPath,javaCommonModulesBasePath+File.separator+"pojo"+File.separator+dto.getModuleName(),"pojo.ftl",dto.getT_ableName()+".java",dto);
        genFileWithTemplate(templateJavaPath,javaSystemModulesBasePath+File.separator+"dto","saveDto.ftl",dto.getT_ableName()+"SaveDto.java",dto);
        genFileWithTemplate(templateJavaPath,javaSystemModulesBasePath+File.separator+"service","service.ftl",dto.getT_ableName()+"Service.java",dto);
        genFileWithTemplate(templateJavaPath,javaSystemModulesBasePath+File.separator+"service"+File.separator+"impl","serviceImpl.ftl",dto.getT_ableName()+"ServiceImpl.java",dto);
        genFileWithTemplate(templateJavaPath,javaSystemModulesBasePath+File.separator+"dto","updateDto.ftl",dto.getT_ableName()+"UpdateByIdDto.java",dto);
        /************** 导入模版生成 start *********************/
        if (dto.getInOut()) {
            dto.setExcelGenerateData(false);
            //创建一个没有时间的ExcelDto 用来生成模版
            genFileWithTemplate(templateJavaPath,javaSystemModulesBasePath+File.separator+"dto","excelDto.ftl",dto.getT_ableName()+"ExcelDto.java",dto);
//            String excelDtoFilePath = javaSystemModulesBasePath + File.separator + "dto" + dto.getT_ableName() + "ExcelDto.java";
            String javaPath = javaSystemModulesBasePath+File.separator+"dto"+File.separator+dto.getT_ableName()+"ExcelDto.java";
            String classPath = javaSystemModulesBasePath+File.separator+"dto"+File.separator+dto.getT_ableName()+"ExcelDto.class";
            String packagePath = "com.lzs.system.modules."+dto.getModuleName()+ ".dto." + dto.getT_ableName() + "ExcelDto";
            try {
                String url = projectPath+File.separator+"vue-admin-template-permission-control"+File.separator+"public"
                        +File.separator+"excel"+File.separator+dto.getT_ableName()+"Import.xlsx";
//                Runtime runtime = Runtime.getRuntime();
//                String buildCmd = "javac -encoding utf-8 -Djava.ext.dirs="+projectPath+"generate_excel_libs" + javaPath;
//                log.info("编译的命令是[{}]",buildCmd);
//                Process exec = runtime.exec(buildCmd);
//                exec.waitFor();
                JavaCompiler compiler =ToolProvider.getSystemJavaCompiler();
                compiler.run(null,null,null, "-encoding", "UTF-8", "-Djava.ext.dirs="+projectPath+"generate_excel_libs",javaPath);
//                Class<?> aClass = Class.forName(classPath);
                ExcelDtoClassLoader loader = new ExcelDtoClassLoader();
                if (JudgeSystemUtil.isWindows()) {
                    loader.setPath("file:/"+classPath);
                }else {
                    loader.setPath("file://"+classPath);
                }
                Class<?> aClass = loader.findClass(packagePath);
                ExportParams exportParams = new ExportParams();
                exportParams.setTitle(dto.getTableComment());
                EasyExcelUtils.createExcel(new ArrayList<>(),url,aClass,exportParams);
                //删除掉没有时间的ExcelDto
                new File(javaPath).delete();
                new File(classPath).delete();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        /************** 导入模版生成 end *********************/
        //重新生成一次
        dto.setExcelGenerateData(true);
        genFileWithTemplate(templateJavaPath,javaSystemModulesBasePath+File.separator+"dto","excelDto.ftl",dto.getT_ableName()+"ExcelDto.java",dto);



        //一对多关系
        if (oneToManyTableDto.getOpen()) {
            File daoFile = new File(javaSystemModulesBasePath + File.separator + "dao" + File.separator + oneToManyTableDto.getJ_oinTable() + "JoinDao.java");
            //判断关联表的代码是否已经生成
            if (!daoFile.exists()) {
                genFileWithTemplate(templateJavaPath,javaSystemModulesBasePath+File.separator+"dao","oneToManyTableDao.ftl",oneToManyTableDto.getJ_oinTable()+"JoinDao.java",dto);
            }
            File pojoFile = new File(javaCommonModulesBasePath + File.separator + "pojo"+ File.separator + dto.getModuleName() + File.separator + oneToManyTableDto.getJ_oinTable()+"Join.java");
            if (!pojoFile.exists()) {
                genFileWithTemplate(templateJavaPath,javaCommonModulesBasePath+File.separator+"pojo"+ File.separator + dto.getModuleName(),"oneToManyTablePojo.ftl",oneToManyTableDto.getJ_oinTable()+"Join.java",dto);
            }
            genFileWithTemplate(templateJavaPath,javaSystemModulesBasePath+File.separator+"dto","getOneToManyTableByPageDto.ftl","Get"+oneToManyTableDto.getJ_oinTable()+"By"+oneToManyTableDto.getJ_oinField()+"PageDto.java",dto);
            genFileWithTemplate(templateJavaPath,javaSystemModulesBasePath+File.separator+"dto","oneToManySaveDto.ftl",oneToManyTableDto.getJ_oinTable()+"SaveJoinDto.java",dto);
            genFileWithTemplate(templateJavaPath,javaSystemModulesBasePath+File.separator+"dto","oneToManyUpdateDto.ftl",oneToManyTableDto.getJ_oinTable()+"UpdateByIdJoinDto.java",dto);

        }

        String jsBasePath = projectPath+File.separator+"vue-admin-template-permission-control"+File.separator+"src"+File.separator;//目标路径【指向你自己的类文件存放路径】

        //js
        //编辑
        genFileWithTemplate(templateJsPath,jsBasePath+"views"+File.separator+"modules"+File.separator+dto.getModuleName()+File.separator+dto.getTableName()+File.separator+"operation","edit.ftl",dto.getTableName()+"Edit.vue",dto);
        //index
        genFileWithTemplate(templateJsPath,jsBasePath+"views"+File.separator+"modules"+File.separator+dto.getModuleName()+File.separator+dto.getTableName(),"index.ftl",dto.getTableName()+"Index.vue",dto);
        //api
        genFileWithTemplate(templateJsPath,jsBasePath+File.separator+"api"+File.separator+"modules"+File.separator+dto.getModuleName(),"api.ftl",dto.getTableName()+"Api.js",dto);
        if (oneToManyTableDto.getOpen()) {
            //一对多index
            genFileWithTemplate(templateJsPath,jsBasePath+"views"+File.separator+"modules"+File.separator+dto.getModuleName()+File.separator+dto.getTableName()+File.separator+"operation","oneToManyTable.ftl",dto.getTableName()+"OneToManyTable.vue",dto);
            //一对多编辑
            genFileWithTemplate(templateJsPath,jsBasePath+"views"+File.separator+"modules"+File.separator+dto.getModuleName()+File.separator+dto.getTableName()+File.separator+"operation","editOneToManyTable.ftl",dto.getTableName()+"EditOneToManyTable.vue",dto);
        }
        //添加菜单权限 列表
        SysMenu sysMenu = new SysMenu();
        sysMenu.setMenuCode(dto.getTable_name()+"");
        sysMenu.setMenuName("["+dto.getTableComment()+"]");
        sysMenu.setParentId("");
        sysMenu.setVueName(dto.getTable_name());
        sysMenu.setVueTitle(dto.getTableComment());
        sysMenu.setVueIcon("el-icon-s-flag");
        sysMenu.setVuePath("/"+dto.getTable_name());
        sysMenu.setVueComponent("Layout");
        sysMenuDao.insert(sysMenu);
        //添加菜单权限 列表
        SysMenu sysMenuList = new SysMenu();
        sysMenuList.setMenuCode(dto.getTable_name()+":list");
        sysMenuList.setMenuName("["+dto.getTableComment()+"]列表");
        sysMenuList.setParentId(sysMenu.getId());
        sysMenuList.setVueName(dto.getTable_name()+"_list");
        sysMenuList.setVueTitle(dto.getTableComment()+"_列表");
        sysMenuList.setVueIcon("el-icon-s-flag");
        sysMenuList.setVuePath("list");
        sysMenuList.setVueComponent("modules/"+dto.getModuleName()+"/"+dto.getTableName()+"/"+dto.getTableName()+"Index");
        sysMenuDao.insert(sysMenuList);
        //添加
        SysMenu sysMenuSave = new SysMenu();
        sysMenuSave.setMenuCode(dto.getTable_name()+":save");
        sysMenuSave.setMenuName("["+dto.getTableComment()+"]添加");
        sysMenuSave.setParentId(sysMenu.getId());
        sysMenuSave.setVueName(dto.getTable_name()+"_save");
        sysMenuSave.setVueTitle(dto.getTableComment()+"_添加");
        sysMenuSave.setVueIcon("el-icon-s-flag");
        sysMenuSave.setVuePath("save");
        sysMenuSave.setVueComponent("");
        sysMenuDao.insert(sysMenuSave);
        //修改
        SysMenu sysMenuEdit = new SysMenu();
        sysMenuEdit.setMenuCode(dto.getTable_name()+":edit");
        sysMenuEdit.setMenuName("["+dto.getTableComment()+"]修改");
        sysMenuEdit.setParentId(sysMenu.getId());
        sysMenuEdit.setVueName(dto.getTable_name()+"_edit");
        sysMenuEdit.setVueTitle(dto.getTableComment()+"_修改");
        sysMenuEdit.setVueIcon("el-icon-s-flag");
        sysMenuEdit.setVuePath("edit");
        sysMenuEdit.setVueComponent("");
        sysMenuDao.insert(sysMenuEdit);
        //删除
        SysMenu sysMenuDelete = new SysMenu();
        sysMenuDelete.setMenuCode(dto.getTable_name()+":delete");
        sysMenuDelete.setMenuName("["+dto.getTableComment()+"]删除");
        sysMenuDelete.setParentId(sysMenu.getId());
        sysMenuDelete.setVueName(dto.getTable_name()+"_delete");
        sysMenuDelete.setVueTitle(dto.getTableComment()+"_删除");
        sysMenuDelete.setVueIcon("el-icon-s-flag");
        sysMenuDelete.setVuePath("delete");
        sysMenuDelete.setVueComponent("");
        sysMenuDao.insert(sysMenuDelete);
        //子表数据
        if (oneToManyTableDto.getOpen()) {
            //添加菜单权限 列表
            SysMenu subTableMenuList = new SysMenu();
            subTableMenuList.setMenuCode(dto.getTable_name()+":subTableData:list");
            subTableMenuList.setMenuName("["+dto.getTableComment()+"内"+oneToManyTableDto.getTableComment()+"]列表");
            subTableMenuList.setParentId(sysMenu.getId());
            subTableMenuList.setVueName(dto.getTable_name()+"-"+oneToManyTableDto.getJoinTable());
            subTableMenuList.setVueTitle(subTableMenuList.getMenuName());
            subTableMenuList.setVueIcon("el-icon-s-flag");
            subTableMenuList.setVuePath("subTableList");
            subTableMenuList.setVueComponent("");
            sysMenuDao.insert(subTableMenuList);
        }
        return CommonResult.OK();
    }

    //通过.flt模板生成file(封装了一下 方便统一调用)
    private static void genFileWithTemplate(String templateDir,String destDir,String templateFileName,String destFileName,Object dto)
    {
        //创建freeMarker配置实例
        Configuration configuration = new Configuration();
        Writer out = null;
        try {
            System.out.println("templateDir = " + templateDir);
            //设置模版路径
            configuration.setDirectoryForTemplateLoading(new File(templateDir));
            //加载模版文件
            Template template = configuration.getTemplate(templateFileName);
            //生成数据
            File docFile = new File(destDir + File.separator + destFileName);
            Files.createParentDirs(docFile);
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
            //输出文件
            template.process(dto, out);
            System.out.println(destFileName+" 模板文件创建成功 !");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != out) {
                try {
                    out.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}
